package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.mapper.TbOrderRecordMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbOrderDetail;
import com.bwie.pojo.TbOrderRecord;
import com.bwie.pojo.TbProdInfo;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.Result;
import com.bwie.utils.TokenUtils;
import com.bwie.vo.PageInfoVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lenovo
 * @description 针对表【tb_order(订单表)】的数据库操作Service实现
 * @createDate 2025-06-20 15:27:23
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements TbOrderService {

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;
    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result getOrderList(PageInfoVo pageInfoVo) {
        String token = request.getHeader("token");
        Integer userId = TokenUtils.tokenUtils(token);

        //构造分页参数
        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        //分页获取订单列表
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        //关键词
        if (StringUtils.isNotEmpty(pageInfoVo.getKeyWord())) {
            wrapper.lambda().like(TbOrder::getProdInfo, pageInfoVo.getKeyWord()).or().eq(TbOrder::getOrderId, pageInfoVo.getKeyWord());
        }

        if (pageInfoVo.getStatus() != null) {
            wrapper.lambda().eq(TbOrder::getOrderStatus, pageInfoVo.getStatus());
        }
        if (pageInfoVo.getType() != null) {
            wrapper.lambda().eq(TbOrder::getOrderType, pageInfoVo.getType());
        }

        wrapper.lambda().orderByDesc(TbOrder::getOrderId);

        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);

        for (TbOrder record : tbOrderPage.getRecords()) {
            List<String> imagesList = tbOrderMapper.getOrderImageList(record.getOrderId());
            List<String> imageList = new ArrayList<>();
            if (imagesList != null && imagesList.size() > 0) {
                for (String s : imagesList) {
                    if (s != null) {
                        List<String> list = JSON.parseArray(s, String.class);
                        imageList.addAll(list);
                    }
                }
            }
            record.setImages(imageList);
        }

        //数据返回之前把前端显示的列表存入缓存

        String key = "order-list" + userId;
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(tbOrderPage.getRecords()));
        return Result.ok().setData(tbOrderPage);
    }


    @Override
    public Result getProdInfo() {
        List<TbProdInfo> prodInfoList = tbProdInfoMapper.selectList(null);

        return Result.ok().setData(prodInfoList);
    }

    @Override
    public Result addProdInfo(List<TbProdInfo> infoList) {
        //通过token获取当前登录人
        String token = request.getHeader("token");
        Integer userId = TokenUtils.tokenUtils(token);
        String userName = TokenUtils.tokenUtilsGetName(token);
        //检查库存
        BigDecimal totalAmount = new BigDecimal(0.0);
        StringBuilder prodNames = new StringBuilder();

        //获取分布式锁
        RLock lock = redissonClient.getLock("order-lock");
        try {
            //加锁
            lock.lock();
            //扣减库存
            for (TbProdInfo tbProdInfo : infoList) {
                TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
                if (tbProdInfo.getBuyNum() > prodInfo.getProdStock()) {
                    throw new RuntimeException();
                }
                //扣减并更新库存
                prodInfo.setProdStock(prodInfo.getProdStock() - tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(prodInfo);

                //计算订单金额
                totalAmount = totalAmount.add(tbProdInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())));

                if (prodNames.length() > 0) {
                    prodNames.append(",");
                    prodNames.append(tbProdInfo.getProdName());
                } else {
                    prodNames.append(tbProdInfo.getProdName());
                }
            }
        } finally {
            //解锁
            lock.unlock();
        }

        //创建订单
        TbOrder tbOrder = new TbOrder();
        //雪花算法生成订单编号
        long id = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo("" + id);

        tbOrder.setOrderType(1);
        tbOrder.setOrderStatus(0);
        tbOrder.setCreatedTime(new Date());
        tbOrder.setCreatedBy(userName);
        tbOrder.setUserId(userId);
        tbOrder.setOrderAmount(totalAmount);
        tbOrder.setProdInfo(prodNames.toString());

        tbOrderMapper.insert(tbOrder);
        //创建订单明细
        for (TbProdInfo tbProdInfo : infoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();

            tbOrderDetail.setOrderId(tbOrder.getOrderId());

            tbOrderDetail.setInfoId(tbProdInfo.getInfoId());
            tbOrderDetail.setProdId(tbProdInfo.getProdId());
            tbOrderDetail.setBuyNum(tbProdInfo.getBuyNum());
            tbOrderDetail.setBuyPrice(tbProdInfo.getProdPrice());
            tbOrderDetail.setCreatedTime(new Date());
            tbOrderDetail.setCreatedBy(userName);

            tbOrderDetailMapper.insert(tbOrderDetail);
        }
        //新增订单记录
        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        tbOrderRecord.setOptRecord("用户创建订单");
        tbOrderRecord.setCreatedTime(new Date());
        tbOrderRecord.setCreatedBy(userName);

        tbOrderRecordMapper.insert(tbOrderRecord);

        return Result.ok();
    }

    @Override
    public void exportOrderList(Integer userId) {
        //创建导出工具
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);
        //从缓存中获取订单列表
        String key = "order-list" + userId;
        String s = stringRedisTemplate.opsForValue().get(key);
        List<TbOrder> tbOrders = JSON.parseArray(s, TbOrder.class);
        //导出excel文件
        excelUtil.exportExcel(response, tbOrders, "订单列表");

    }
}




